package com.example.hello.controller;

import com.example.hello.common.Result;
import com.example.hello.common.JwtUtils;
import com.example.hello.entity.Emp;
import com.example.hello.service.EmpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
public class AuthController {

    @Autowired
    private EmpService empService;

    @Autowired
    private JwtUtils jwtUtils;

    public static class LoginRequest {
        public String username;
        public String password;
    }

    @PostMapping("/login")
    public Result<Object> login(@RequestBody LoginRequest request) {
        if (request == null || request.username == null || request.password == null) {
            return Result.error("用户名或密码错误", null);
        }

        Emp emp = empService.selectByUsername(request.username);
        if (emp == null || emp.getPassword() == null || !emp.getPassword().equals(request.password)) {
            return Result.error("用户名或密码错误", null);
        }

        Map<String, Object> claims = new HashMap<>();
        claims.put("id", emp.getId());
        claims.put("username", emp.getUsername());
        String token = jwtUtils.generateToken(claims);

        Map<String, Object> data = new HashMap<>();
        data.put("id", emp.getId());
        data.put("username", emp.getUsername());
        data.put("name", emp.getName());
        data.put("token", token);
        return Result.success(data);
    }
}


